﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace CSharpTools {
    class Logger {
        static public string logFile = $"{Directory.GetCurrentDirectory()}/Log/Log_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.txt";
        // 输出同时写日志
        static public void WriteLog(string str) {
            Directory.CreateDirectory(Path.GetDirectoryName(logFile));
            File.AppendAllText(logFile, str);
            Console.Write(str);
        }
    }
    class XmlTools {
        public static List<XmlNode> SearchAllNodesByName(string xmlDocPath, string targetNodeName) {
            var result = new List<XmlNode>();
            if (string.IsNullOrEmpty(targetNodeName)) { return result; }
            // 不加这一行就不支持 GB2312 编码
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlDocPath);
            // 
            SearchIterativelyByName(result, xmlDoc, "");
            throw new NotImplementedException();
            return result;
        }
        public static void SearchIterativelyByName(List<XmlNode> listResult, XmlNode node, string targetNodeName) {
            if(listResult == null) {
                listResult = new List<XmlNode>();
            }
            if (node == null || listResult == null) {
                // 抛出异常或处理错误情况
                throw new ArgumentNullException("root or listResult cannot be null.");
            }

            Stack<XmlNode> stack = new Stack<XmlNode>();
            stack.Push(node);

            while (stack.Count > 0) {
                XmlNode currentNode = stack.Pop();

                if (currentNode.Name == targetNodeName) {
                    listResult.Add(currentNode);
                }

                if (currentNode.HasChildNodes) {
                    foreach (XmlNode childNode in currentNode.ChildNodes) {
                        stack.Push(childNode);
                    }
                }
            }
        }
    }
    class VCXXmlTools {
        /// <summary>
        /// 获取包含输入库列表的 AdditionalDependencies 的 XmlNode 节点
        /// </summary>
        /// <param name="xmlDoc"> 读取为 XmlDocument 的 vcxproj 文件 </param>
        /// <param name="isDebug"> 读取 Debug 配置还是 Release 配置 </param>
        /// <returns></returns>
        public static XmlNode? GetOriginalInputLibsNode(string xmlDocPath, bool isDebug = true) {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlDocPath);
            if (xmlDoc == null) { return null; }
            if (!xmlDoc.HasChildNodes) {
                return null;
            }
            foreach (XmlNode node in xmlDoc.ChildNodes) {
                if (!node.HasChildNodes) {
                    continue;
                }
                foreach (XmlNode node2 in node.ChildNodes) {
                    // 查找输入库节点位置
                    if (node2.Name == "ItemDefinitionGroup") {
                        if (node2.Attributes == null) {
                            continue;
                        }
                        foreach (XmlAttribute attr in node2.Attributes) {
                            if (!attr.Value.Contains(isDebug ? "Debug" : "Release" + "|Win32")) {
                                continue;
                            }
                            foreach (XmlNode itemDefinitionGroupChild in node2.ChildNodes) {
                                if (itemDefinitionGroupChild.Name != "Link") {
                                    continue;
                                }
                                foreach (XmlNode linkChild in itemDefinitionGroupChild.ChildNodes) {
                                    if (linkChild.Name != "AdditionalDependencies") {
                                        continue;
                                    }
                                    return linkChild;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
        public static List<string>? GetOriginalInputLibsList(string xmlDocPath, bool isDebug = true) {
            if (xmlDocPath == null) { return null; }
            XmlNode originInputLibsNode = GetOriginalInputLibsNode(xmlDocPath);
            if (originInputLibsNode == null) { return null; }

            return originInputLibsNode.InnerText.Split(";").ToList();
        }

        /// <summary>
        /// 获取引用项目列表的 XmlNode
        /// </summary>
        /// <param name="xmlDoc"> 读取为 XmlDocument 的 vcxproj 文件 </param>
        /// <returns></returns>
        public static XmlNode? GetNewDependenciesNode(string xmlDocPath) {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlDocPath);
            if (xmlDoc == null) { return null; }
            if (!xmlDoc.HasChildNodes) {
                return null;
            }
            foreach (XmlNode node in xmlDoc.ChildNodes) {
                if (!node.HasChildNodes) {
                    continue;
                }
                foreach (XmlNode node2 in node.ChildNodes) {
                    // 删除 ProjectReference
                    for (int i = 0; i < node2.ChildNodes.Count; i++) {
                        if (node2.ChildNodes[i].Name != "ProjectReference") {
                            continue;
                        }
                        return node2;
                    }
                }
            }
            return null;
        }
        public static List<string>? GetDependenciesList(string xmlDocPath) {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlDocPath);
            if (xmlDoc == null) { return null; }
            XmlNode dependenciesNode = GetNewDependenciesNode(xmlDocPath);
            if (dependenciesNode == null) {
                return null;
            }
            List<string> dependenciesStrList = new List<string>();
            foreach (XmlNode projectReferenceNode in dependenciesNode.ChildNodes) {
                foreach (XmlAttribute attribute in projectReferenceNode.Attributes) {
                    if (attribute.Name != "Include") {
                        continue;
                    }
                    int startIndex = attribute.InnerText.LastIndexOf(@"\") + 1;
                    string result = attribute.InnerText.Substring(startIndex, attribute.InnerText.Length - startIndex - 8);
                    dependenciesStrList.Add(result);
                }
            }
            return dependenciesStrList;
        }

        /// <summary>
        /// 获取完整的输入库列表，带lib后缀
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <param name="isDebug"></param>
        /// <returns></returns>
        public static List<string>? GetCompleteInputLibsList(string xmlDocPath, bool isDebug = true) {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlDocPath);
            if (xmlDoc == null) { return null; }
            // 
            List<string> listOriginInputLibs = GetOriginalInputLibsList(xmlDocPath);
            if (listOriginInputLibs == null) {
                Logger.WriteLog($"🔴项目 {xmlDocPath} 的输入库获取为空，用空列表代替。\n");
                listOriginInputLibs = new List<string>();
            }
            // 
            List<string> listDependencies = GetDependenciesList(xmlDocPath);
            if (listDependencies == null) {
                Logger.WriteLog($"🔴项目 {xmlDocPath} 的引用获取为空，用空列表代替。\n");
                listDependencies = new List<string>();
            }
            // 
            List<string> listComplete = new List<string>();
            listComplete.AddRange(listOriginInputLibs);
            listComplete.AddRange(listDependencies);
            // 除去不需要的元素
            listComplete = listComplete.Where(s => (
                !string.IsNullOrEmpty(s))
                && s != "%(AdditionalDependencies)"
            ).ToList();
            // 有的库不需要加 10 的后缀，直接就是 .lib，比如说 lib_json,
            // 所以这里直接先给他加好，然后再在下面的排除名单里加上
            var listLibsThatDoesNotNeed10Postfix = new List<string> { "lib_json" };
            listComplete = listComplete.Select((lib) => {
                if (listLibsThatDoesNotNeed10Postfix.Contains(lib)) {
                    return lib + ".lib";
                }
                return lib;
            }).ToList();
            // 给库加后缀
            string postfix = isDebug ? "10d.lib" : "10.lib";
            var listLibsThatDontModify = new List<string> { "SensAPI.lib", "acge17.lib", "acad.lib", "acdb17.lib", "acge17.lib", "lib_json.lib" };
            for (int i = 0; i < listComplete.Count; i++) {
                if (listLibsThatDontModify.Contains(listComplete[i])) {
                    continue;
                }
                else if (listComplete[i].EndsWith(".lib")) {
                    continue;
                }
                listComplete[i] = listComplete[i] + postfix;
            }
            // 
            return listComplete;
        }
        /// <summary>
        /// 将搜索目录如 IncludePath 等修改到新的
        /// </summary>
        /// <param name="xmlDocPath"></param>
        /// <param name="isDebug"></param>
        /// <returns></returns>
        public static bool ModifyVCSearchDirectoriesToNew(string xmlDocPath, bool isDebug = true) {
            // TODO: 新增函数，修改搜索目录
            return false;
        }
    }
    class VCXmlTools {
        public static XmlNode? GetInputLibsNode(string xmlDocPath, bool isDebug = true) {
            var xmlDoc = new XmlDocument();
            // 不加这一行就不支持 GB2312 编码
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            xmlDoc.Load(xmlDocPath);

            if (xmlDoc == null) { return null; }
            if (!xmlDoc.HasChildNodes) {
                return null;
            }

            foreach (XmlNode node in xmlDoc.ChildNodes) {// 第一层：两个子节点，xml 规格定义和主节点 VisualStudioProject
                if (!node.HasChildNodes) {
                    continue;
                }
                foreach (XmlNode node2 in node.ChildNodes) {// 第二层：六个子节点，包含 Configurations， 找到他
                    if(node2.Name != "Configurations") {
                        continue;
                    }
                    foreach (XmlNode node3 in node2.ChildNodes) {// 第三层：各个配置Configuration节点
                        var attrsOfNode3 = node3.Attributes;
                        if (attrsOfNode3 == null) {
                            continue;
                        }
                        var attr = attrsOfNode3.GetNamedItem("Name");
                        if (attr == null) {
                            continue;
                        }
                        else if (attr.InnerText != (isDebug ? "Debug|Win32" : "Release|Win32")) {
                            continue;
                        }
                        foreach (XmlNode node4 in node3.ChildNodes) {// 第四层：Configuration 下的各种 Tool 节点，包含 VCLinkerTool
                            var attrsOfNode4 = node4.Attributes;
                            if (attrsOfNode4 == null) {
                                continue;
                            }
                            var attrNameNodeOfNode4 = attrsOfNode4.GetNamedItem("Name");
                            if (attrNameNodeOfNode4 == null) {
                                continue;
                            }
                            var attrNameOfNode4 = (XmlAttribute)attrNameNodeOfNode4;
                            if (attrNameOfNode4.InnerText != "VCLinkerTool") {
                                continue;
                            }
                            var attrAdditionalDependenciesNode = attrsOfNode4.GetNamedItem("AdditionalDependencies");
                            // 如果没找到就创建一个然后返回
                            if(attrAdditionalDependenciesNode == null) {
                                var newAttrNode = xmlDoc.CreateAttribute("AdditionalDependencies");
                                attrsOfNode4.InsertAfter(newAttrNode, attrNameOfNode4);
                                attrAdditionalDependenciesNode = newAttrNode;
                            }
                            return attrAdditionalDependenciesNode;
                        }
                    }
                }
            }
            return null;
        }
    }
    class SlnTools {
        public static string? GenerateSlnCodePhase(List<string> listProjectNames) {
            if (listProjectNames == null || listProjectNames.Count == 0) {
                return null;
            }
            // 去掉空的
            StringBuilder sb = new StringBuilder();
            listProjectNames = listProjectNames.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            foreach (string projectName in listProjectNames) {
                sb.Append($"Project(\"{{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}}\") = \"{projectName}\", \"..\\{projectName}\\{projectName}.vcproj\", \"{{B6BC4E64-F042-44C4-807F-2F0CE9B5516C}}\"\r\n" +
                    $"EndProject\n");
            }
            return sb.ToString();
        }
        public static bool AddProjectToSln(string slnPath, List<string> listProjects) {
            if (listProjects == null || listProjects.Count == 0) {
                return false;
            }
            // 读取 sln
            StreamReader sr = new StreamReader(slnPath);
            string content = sr.ReadToEnd();
            sr.Close();
            if (string.IsNullOrEmpty(content)) {
                return false;
            }
            // 寻找插入点，即最后一次出现 EndProject 的位置
            string targetSeq = "EndProject";
            int insertPoint = content.LastIndexOf(targetSeq) + targetSeq.Length + 1;
            // 生成要插入的内容
            string contentToBeInsert = GenerateSlnCodePhase(listProjects);
            if (string.IsNullOrEmpty(contentToBeInsert)) {
                return false;
            }
            // 插入
            content = content.Insert(insertPoint, contentToBeInsert);
            // 将修改后的内容写回文件
            StreamWriter sw = new StreamWriter(slnPath);
            sw.Write(content);
            sw.Close();

            return true;
        }
    }
    static class StringEXT {
        public static string Replace(this string str, string old, string @new, StringComparison comparison) {
            @new = @new ?? "";
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(@new, comparison))
                return str;
            int foundAt = 0;
            while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1) {
                str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
                foundAt += @new.Length;
            }
            return str;
        }
    }
    // 将我现在使用的添加引用的依赖管理方式变为传统的添加输入库
    internal class ChangeDependenciesFormatToInputLibrary {
        
        static List<KeyValuePair<string,string>> GetArgsDict(string[] args) {
            var listResArgs = new List<KeyValuePair<string,string>>();
            List<string> listinputArgs = args.ToList();
            // 
            string strSingleCommand = "";
            string strParamsForSingleCommand = "";
            // 对每一个参数
            foreach (string arg in listinputArgs) {
                // 如果以 '-' 开始，则是代表新的命令
                if (arg.StartsWith("-")) {
                    // 如果不为空，则说明之前遇到了命令，现在已经读到了下一个命令，
                    // 所以保存上一个命令及其参数到字典，然后清空缓存，保存新命令
                    if (strSingleCommand != "") {
                        listResArgs.Add(new KeyValuePair<string, string>(strSingleCommand, strParamsForSingleCommand));
                    }
                    strSingleCommand = arg.Replace("-", "");
                    strParamsForSingleCommand = "";
                    continue;
                }
                // 当命令参数为空时，不加空格
                if (strParamsForSingleCommand == "") {
                    strParamsForSingleCommand += arg;
                }
                // 加空格
                else {
                    strParamsForSingleCommand += " " + arg;
                }
            }
            listResArgs.Add(new KeyValuePair<string, string>(strSingleCommand, strParamsForSingleCommand));
            // 
            return listResArgs;
        }
        //static XmlNode ?SearchXml(string strLabelName, string strAttributeName, string strAttributeValue) {
        //    return null;
        //}

        static string GetHelpMessage() {
            return "关于帮助信息，请询问开发者。";
        }

        static void GetInputLibsFromFileOrFolder(List<string> listPathes) {
            foreach (var path in listPathes) {
                if (File.Exists(path)) {
                    Logger.WriteLog($"项目 {Path.GetFileName(path)} 输入库列表:\n{string.Join(" ", VCXXmlTools.GetCompleteInputLibsList(path))}\n\n");
                }
                else if (Directory.Exists(path)) {
                    var files = Directory.GetFiles(path, "*.vcxproj");
                    var listPathesToVCXFile = new List<string>();
                    listPathesToVCXFile.AddRange(files);
                    // 递归
                    GetInputLibsFromFileOrFolder(listPathesToVCXFile);
                }
                else {
                    Logger.WriteLog($"给出的参数 {path} 不是有效的路径！\n\n");
                }
            }
        }
        static void TransferInputLibsFromVCX_2_VC(List<string> listPathes) {
            foreach (var path in listPathes) {
                if (File.Exists(path)) {
                    // 获取完整的输入库列表
                    string completeInputLibs = string.Join(" ", VCXXmlTools.GetCompleteInputLibsList(path));
                    // 打开旧 vcproj 项目文件 
                    string oldVCProjectPath = path.Replace("vcxproj", "vcproj");
                    // 获取节点
                    var oldVCInputLibsNode = VCXmlTools.GetInputLibsNode(oldVCProjectPath);
                    // 替换
                    oldVCInputLibsNode.InnerText = completeInputLibs;
                    // 保存
                    System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    var enc = System.Text.Encoding.GetEncoding("gb2312");
                    using (TextWriter sw = new StreamWriter(path.Replace("vcxproj", "vcproj"), false, enc)){ //Set encoding
                            oldVCInputLibsNode.OwnerDocument.Save(sw);
                    }
                    Logger.WriteLog($"项目 {oldVCProjectPath} 的输入库已被修改为如下：\n{completeInputLibs}\n");
                }
                else if (Directory.Exists(path)) {
                    Logger.WriteLog($"给出的参数为文件夹，自动获取文件夹其中的项目文件！\n");
                    // 从文件夹里获取项目文件具体位置，然后构造文件列表
                    var files = Directory.GetFiles(path, "*.vcxproj");
                    var listPathesToVCXFile = new List<string>();
                    listPathesToVCXFile.AddRange(files);
                    // 递归
                    TransferInputLibsFromVCX_2_VC(listPathesToVCXFile);
                }
                else {
                    Logger.WriteLog($"给出的参数 {path} 不是有效的路径！\n");
                }
            }
            Logger.WriteLog($"TransferInputLibsFromVCX_2_VC 命令已完成，以下项目对应的vcproj项目文件已修改：\n{string.Join("\n", listPathes)}\n\n");
        }
        static void GenerateSlnCodePhaseForAddingNewProject(List<string> listProjectNames) {
            if(listProjectNames == null || listProjectNames.Count == 0) {
                Logger.WriteLog($"Task : GenerateSlnCodePhaseForAddingNewProject\n\t给出的项目列表为空！\n\n");
                Logger.WriteLog($"Task : GenerateSlnCodePhaseForAddingNewProject\n\t参数应为项目列表，以空格分隔，如\"AP09_7_047Singleton AP09_7_047Snowflake AP09_7_047SplashWnd\"\n\n");
                return;
            }
            listProjectNames = listProjectNames.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            Logger.WriteLog($"复制下面段落到新版 sln 文件中：\n\n");
            foreach (string projectName in listProjectNames) {
                Logger.WriteLog($"Project(\"{{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}}\") = \"{projectName}\", \"..\\{projectName}\\{projectName}.vcproj\", \"{{B6BC4E64-F042-44C4-807F-2F0CE9B5516C}}\"\r\n" +
                    $"EndProject\n");
            }
            Logger.WriteLog($"\n然后进入VS重新加载他们，会提示加载失败，但其实没失败，保存退出，然后把sln里vcproj替换为vcxproj，再次加载即可。\n\n");
        }
        static void GetFileNameFromDrag(List<string> listProjectNames) {
            if (listProjectNames == null || listProjectNames.Count == 0) {
                Logger.WriteLog($"Task : GetFileNameFromDrag\n\t给出的项目列表为空！\n\n");
                Logger.WriteLog($"Task : GetFileNameFromDrag\n\t用于通过拖拽文件夹的方式批量获取他们的文件名，方便一些操作\n\t参数应为项目列表，以空格分隔，如\"\"D:\\VC\\ObjectPRX 2024\\sln\\AP11_7_108AdminManager\" \"D:\\VC\\ObjectPRX 2024\\sln\\AP11_5_043ElmListWorkExt\"\"\n\n");
                return;
            }
            listProjectNames = listProjectNames.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            Logger.WriteLog($"复制下面段落到新版 sln 文件中：\n\n");
            foreach (string projectName in listProjectNames) {
                Logger.WriteLog($"{Path.GetFileName(projectName)} ");
            }
            Logger.WriteLog("\b\n");
            Logger.WriteLog($"\n然后进入VS重新加载他们，会提示加载失败，但其实没失败，保存退出，然后把sln里vcproj替换为vcxproj，再次加载即可。\n\n");
        }
        static void AddProjectToSln(List<string> listArgs) {
            if (listArgs == null || listArgs.Count == 0) {
                Logger.WriteLog($"Task : AddProjectToNewSln\n\t给出的项目列表为空！\n\n");
                Logger.WriteLog($"Task : AddProjectToNewSln\n\t参数应为项目列表，以空格分隔，如\"AP09_7_047Singleton AP09_7_047Snowflake AP09_7_047SplashWnd\"\n\n");
                return;
            }
            listArgs = listArgs.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            // 获取参数 1：slnPath 2：是否是给新版sln添加
            string slnPath = listArgs[0];
            if (!File.Exists(slnPath)) {
                Logger.WriteLog("给出的 sln 文件不存在！\n\n");
                return;
            }

            string strIsNewSln = listArgs[1];
            bool isNewSln = false;
            if(strIsNewSln == "true") {
                isNewSln = true;
            }
            else if (strIsNewSln == "false") {
                isNewSln = false;
            }
            else {
                Logger.WriteLog($"第二个参数 \"{strIsNewSln}\" 应为 true 或者 false，以指示是将项目添加到新版还是旧版，因为新版需要转换，而旧版不需要，true指新版，false指旧版。\n\n");
                return;
            }

            listArgs.Remove(slnPath);
            listArgs.Remove(strIsNewSln);
            // 
            var listProjectNames = new List<string>();
            foreach (string path in listArgs) {
                if (File.Exists(path)) {
                    listProjectNames.Add(Path.GetFileNameWithoutExtension(path));
                }
                else if (Directory.Exists(path)) {
                    listProjectNames.Add(Path.GetFileName(path));
                }
                else {
                    Logger.WriteLog($"给出的路径：{path} 不存在！\n\n");
                    return;
                }
            }
            // 
            SlnTools.AddProjectToSln(slnPath, listProjectNames);
            //
            // 
            if (isNewSln) {
                Logger.WriteLog($"接下来请打开 VS，根据 VS 提示，重新加载解决方案，然后找到新添加的项目，他们现在应该是加载失败的状态，\n" +
                    $"在列表最下方，重新加载他们，转换完成后保存解决方案，在此按下回车，以替换 vcproj 到 vcxproj。\n\n");
                Console.ReadLine();
                // 
                string content = File.ReadAllText(slnPath);
                string updatedContent = content.Replace(".vcproj", ".vcxproj");
                File.WriteAllText(slnPath, updatedContent);
            }
            else {
                Logger.WriteLog($"接下来请打开 VS，加载项目，使其刷新项目的 Hash。\n\n");
            }
        }
        /// <summary>
        /// 参数示例 [1：源宏] [2...：项目名]
        /// </summary>
        /// <param name="listArgs"></param>
        static void ReplaceAndAddImportMarco(List<string> listArgs) {
            if (listArgs == null || listArgs.Count == 0) {
                Logger.WriteLog($"Task : ReplaceImportMarco\n\t给出的项目列表为空！\n\n");
                Logger.WriteLog($"Task : ReplaceImportMarco\n\t参数应为项目列表，以空格分隔，如\"AP09_7_047Singleton AP09_7_047Snowflake AP09_7_047SplashWnd\"\n\n");
                return;
            }
            listArgs = listArgs.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            //
            string sourceMarco = listArgs[0];
            if (string.IsNullOrEmpty(sourceMarco)) {
                Logger.WriteLog("没有给出宏！\n\n");
                return;
            }
            listArgs.Remove(sourceMarco); 
            // 
            var listProjectNames = new List<string>();
            foreach (string path in listArgs) {
                if (File.Exists(path)) {
                    listProjectNames.Add(Path.GetFileNameWithoutExtension(path));
                }
                else if (Directory.Exists(path)) {
                    listProjectNames.Add(Path.GetFileName(path));
                }
                else {
                    Logger.WriteLog($"给出的路径：{path} 不存在！\n\n");
                    return;
                }
            }
            // 
            string pattern = "AP\\d+_\\d+_\\d+";
            foreach (string project in listProjectNames) {
                Match match = Regex.Match(project, pattern);
                string matchCode = match.Value;
                // 去掉了编号
                string name = Regex.Replace(project, pattern, "");
                string headerFilePath = "D:\\VC\\ObjectPRX 2024\\inc\\" + name + ".h";
                if (!File.Exists(headerFilePath)) {
                    Logger.WriteLog($"文件 {headerFilePath} 不存在！继续处理其他文件...\n\n");
                    continue;
                }
                System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                string content = File.ReadAllText(headerFilePath, Encoding.GetEncoding("gb2312"));
                // 替换宏
                content = content.Replace(sourceMarco, $"{matchCode}_{name}_Exp");
                content = content.Replace($"class {name}", $"class {matchCode}_{name}_Exp {name}");
                // 不存在目标 ShareHeader 时才添加
                if (content.IndexOf($"{project}ShareHeader.h") < 0) {
                    string matchTarget = ".h\"";
                    int insertPoint = content.LastIndexOf(matchTarget) + matchTarget.Length;
                    content = content.Insert(insertPoint, $"\r\n#include \"{project}ShareHeader.h\"\r\n");
                }
                File.WriteAllText(headerFilePath, content, Encoding.GetEncoding("gb2312"));
            }
        }
        static void Main(string[] args) {
            // 帮助信息
            if (args.Length == 0) {
                Logger.WriteLog(GetHelpMessage() + "\n");
                return;
            }
            // 解析参数为字典
            var dictParams = GetArgsDict(args);
            // 如果有 -h 继续输出帮助信息
            foreach (var arg in dictParams) {
                // 参数判空检查
                if (string.IsNullOrEmpty(arg.Key) || string.IsNullOrEmpty(arg.Value)) {
                    Logger.WriteLog($"当前命令为空或参数为空！\n");
                    continue;
                }
                //
                Logger.WriteLog($"接收命令： -{arg.Key} {arg.Value} \n\n");
                // 解决路径带空格问题，不过只能针对我们这个 ObjectPRX 的路径
                string replacedSpaceArgValue = arg.Value.Replace("ObjectPRX 2024", "ObjectPRX_2024", StringComparison.OrdinalIgnoreCase);
                //string replacedSpaceArgValue = Regex.Replace(arg.Value, "ObjectPRX 2024", "ObjectPRX_2024", RegexOptions.IgnoreCase);
                List<string> listArgs = new List<string>(replacedSpaceArgValue.Split(" "));
                listArgs = listArgs.Select(path => path.Replace("ObjectPRX_2024", "ObjectPRX 2024")).ToList();
                // 分命令执行
                if (arg.Key == "h") {
                    Logger.WriteLog(GetHelpMessage() + "\n");
                    return;
                }
                else if (arg.Key == "GetInputLibs") {
                    GetInputLibsFromFileOrFolder(listArgs);
                }
                else if (arg.Key == "TransferInputLibsFromVCX_2_VC") {
                    TransferInputLibsFromVCX_2_VC(listArgs);
                }
                else if (arg.Key == "GenerateSlnCodePhaseForAddingNewProject") {
                    GenerateSlnCodePhaseForAddingNewProject(listArgs);
                }
                else if (arg.Key == "GetFileNameFromDrag") {
                    GetFileNameFromDrag(listArgs);
                }
                else if (arg.Key == "AddProjectToSln") {
                    AddProjectToSln(listArgs);
                }
                else if (arg.Key == "ReplaceAndAddImportMarco") {
                    ReplaceAndAddImportMarco(listArgs);
                }
                else {
                    Logger.WriteLog($"未知命令： {arg.Key} ！ \n\n");
                }

            }
            //
            Logger.WriteLog($"日志保存在 {Logger.logFile} \n");
            //
            Console.ReadLine();
        }
    }
}